<script setup lang="ts">
/**
 * @see {@link https://vuejs.org/api/sfc-script-setup.html#defineoptions}
 */
import {
  pledgeRobotList,
  pledgeRobotAdd,
  updateEnableSale,
  pledgeRobotDel,
  pledgeRobotUpdate
} from "@/api/user";
import { ElMessage } from 'element-plus';
import { formatTimestamp } from "@/utils/index";

import { UserPageVO } from "@/api/user/types";
import ProductModal from "./components/product-modal/index.vue";

defineOptions({
  name: "User",
  inheritAttrs: false,
});
const queryFormRef = ref(ElForm); // 查询表单
const visibleModal = ref(false);
const loading = ref(false);
const total = ref(0);
const productInfo = ref<any>({});
const modalKey = ref(0); // 用于刷新组件

const queryParams = ref({
  page: 1,
  ps: 10,
  s_title: ""
});

const userList = ref<UserPageVO[]>();

watch(visibleModal, (newValue) => {
  if (!newValue) {
    modalKey.value = new Date().getTime();
    return productInfo.value = {};
  }
});


/**
 * 查询
 */
function handleQuery() {
  loading.value = true;
  pledgeRobotList(queryParams.value)
    .then(({ data }) => {
      userList.value = data.data;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.value.page = 1;
  handleQuery();
}
// 创建产品
const submitForm = (params: any) => {
  pledgeRobotAdd(params).then((res: any) => {
    if (res.code === 200) {
      visibleModal.value = false;
      ElMessage.success('创建成功!');
      handleQuery();
    }
  })
};

// 上下架
const handUpdateEnableSale = (params: any) => {
  updateEnableSale({
    id: params.id,
    enable_sale: params.enable_sale === 1 ? 2 : 1
  }).then((res: any) => {
    if (res.code === 200) {
      ElMessage.success('操作成功!');
      handleQuery();
    }
  });
};

// 删除
const handPledgeRobotDel = (params: any) => {
  pledgeRobotDel({
    ids: [params.id],
  }).then((res: any) => {
    if (res.code === 200) {
      ElMessage.success('删除成功!');
      handleQuery();
    }
  });
};

// 编辑
const handEdit = (params: any) => {
  productInfo.value = params;
  modalKey.value = new Date().getTime();
  visibleModal.value = true;
};

const handUpdate = (params: any) => {
  pledgeRobotUpdate(params).then((res: any) => {
    if (res.code === 200) {
      productInfo.value = {};
      visibleModal.value = false;
      ElMessage.success('修改成功!');
      handleQuery();
    }
  });
};

onMounted(() => {
  handleQuery(); // 初始化用户列表数据
});
</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">

      <el-col :lg="24" :xs="24">
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="产品名称" prop="name">
              <el-input v-model="queryParams.s_title" placeholder="输入产品名称" clearable style="width: 200px"
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery"><i-ep-search />搜索</el-button>
              <el-button @click="resetQuery">
                <i-ep-refresh />
                重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button v-hasPerm="['pledgeRobot:add']" type="primary" @click="visibleModal = true">新建</el-button>
                <!-- <el-button type="danger"><i-ep-delete />批量删除</el-button> -->
              </div>
            </div>
          </template>
          <el-table v-hasPerm="['pledgeRobot:pageList']" v-loading="loading" border :data="userList"
            tooltip-effect="dark">
            <el-table-column type="selection" align="center" width="50" />
            <el-table-column label="ID" align="center" prop="id" width="100" />
            <el-table-column label="排序值" align="center" prop="sort" width="100" />
            <el-table-column label="产品名称" align="center" prop="title" />
            <el-table-column label="价格" align="center" prop="price" />
            <el-table-column label="可用天数" align="center" prop="valid_days" />
            <el-table-column label="启动资金" align="center" prop="init_fund" />
            <el-table-column label="预期收益" align="center" prop="about_income_rate" />
            <el-table-column label="最低收益" align="center" prop="income_rate_min" />
            <el-table-column label="最高收益" align="center" prop="income_rate_max" />
            <el-table-column label="创建时间" align="center" :width="160">
              <template #default="scope">
                <span>{{ formatTimestamp(scope.row.created_at * 1000) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" align="center" width="220">
              <template #default="scope">
                <el-button v-hasPerm="['pledgeRobot/:update']" type="primary" size="small"
                  @click="handEdit(scope.row)">编辑</el-button>
                <el-button v-hasPerm="['pledgeRobot:updateEnableSale']" type="primary" size="small"
                  @click="handUpdateEnableSale(scope.row)">{{ scope.row.enable_sale
                    === 1 ? "上架" : "下架" }} </el-button>
                <el-popconfirm title="是否要删除当前产品?" @confirm="handPledgeRobotDel(scope.row)">
                  <template #reference>
                    <el-button v-hasPerm="['pledgeRobot:del']" type="primary" size="small">删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page"
            v-model:limit="queryParams.ps" @pagination="handleQuery" />
        </el-card>
      </el-col>
    </el-row>

    <product-modal :key="modalKey" :visible="visibleModal" :product="productInfo" @close="visibleModal = false"
      @submit="submitForm" @update="handUpdate" />
  </div>
</template>
